package com.pro.wallet;

import android.os.Build;
import android.os.Bundle;

import com.hashkey.wxbasemodule.base.SimpleBaseActivity;
import com.hashkey.wxbasemodule.utils.LogUtil;
import com.pro.wallet.config.AppConfig;
import com.pro.wallet.manager.PageRouterManager;

import java.util.UUID;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.embedding.engine.dart.DartExecutor;

public class SplashActivity extends SimpleBaseActivity {
    private long MAX_WAIT_TIME = 2500;
    private long MIN_WAIT_TIME = 1000;

    private boolean isForwarding = false;
    private long enterTime = 0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.enterTime = System.currentTimeMillis();

        flutterEngineInit();

        setContentView(R.layout.activity_splash);

        delayToForward();
    }

    // 引擎初始化
    private void flutterEngineInit() {
        AppConfig.mainEngineId = UUID.randomUUID().toString();

        LogUtil.i("engine====", AppConfig.mainEngineId);

        engineInit(AppConfig.mainEngineId, AppConfig.FlutterConfig.FLUTTER_INIT_ROUTE_MAIN);
    }

    private void engineInit(String engineId, String initRoute) {
        FlutterEngine flutterEngine = new FlutterEngine(this);

        flutterEngine.getNavigationChannel().setInitialRoute(initRoute);

        flutterEngine.getDartExecutor().executeDartEntrypoint(
                DartExecutor.DartEntrypoint.createDefault()
        );

        FlutterEngineCache.getInstance().put(engineId, flutterEngine);
    }

    private void delayToForward() {
        new Thread(
                () -> {
                    sleep(MAX_WAIT_TIME);
                    forwardToNextActivity(false, null);
                }
        ).start();
    }

    private void sleep(Long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void forwardToNextActivity(Boolean hasNewVersion, Build.VERSION version) {
        if (!isForwarding) { // 如果正在跳转或已经跳转到下一个界面，则不再重复执行跳转
            isForwarding = true;
            long currentTime = System.currentTimeMillis();
            long timeSpent = currentTime - enterTime;
            if (timeSpent < MIN_WAIT_TIME) {
                sleep(MIN_WAIT_TIME - timeSpent);
            }

            jumpToMain();
        }
    }

    private void jumpToMain() {
        runOnUiThread(() -> {
            PageRouterManager.getInstance().openPageByUrl(this, PageRouterManager.NATIVE_PAGE_URL , null);

            finish();
        });
    }

}
